package service

import (
	"github.com/benji/software/Entities"
	"github.com/benji/software/common"
	"github.com/benji/software/dao"
	"github.com/benji/software/model"
	log "github.com/sirupsen/logrus"
	"strconv"
	"strings"
)

func CreateUser( user *Entities.User)error {
	mUser := model.User{}
	mUser.EMail = user.EMail
	mUser.Name = user.Name
	mUser.Phone = user.Phone
	mUser.Password = user.Password
	mUser.Role = -1
	//默认不绑定
	if err := dao.CreateUser(&mUser);err != nil {
		log.Errorf("service fail to create user")
		return err
	}
	log.Infof("id: %v",mUser.ID)
	user.ID = mUser.ID
	return nil
}
func VerifyUser(name string,password string)(bool,int){
	user,err := dao.GetUserByName(name)
	if err != nil {
		log.Errorf("Fail to get user: %v",err)
		return false,0
	}
	log.Infof("user: %+v",user)
	if user.Password == password {
		return true,user.ID
	}
	return false,0
}
func GetUserInfo(id int)(*Entities.User,error){
	user,err := dao.GetUserByID(id)
	if err != nil {
		log.Errorf("service fail to GetUserInfo,err:%v",err)
		return nil,err
	}
	res := Entities.User{}
	res.ID = user.ID
	res.Role = user.Role
	res.Password = ""
	res.Name = user.Name
	res.EMail = user.EMail
	res.Phone = user.Phone
	return &res,nil
}
func GetUserScore(id int)(*Entities.Scores,error){
	data,err := dao.GetHistoryByStudentID(id)
	if err != nil {
		log.Errorf("Fail to get student history,err:%v",err)
		return nil,err
	}
	right := 0
	wrong := 0
	res := Entities.Scores{}
	recentHistory := make([]Entities.History,0)
	for index,val := range data{
		rightList := string2IntList(val.RightAnswer)
		wrongList := string2IntList(val.WrongAnswer)
		right += len(rightList)
		wrong += len(wrongList)
		if index < common.RECENT_SIZE {
			temp := Entities.History{}
			temp.ID = val.ID
			temp.Grades = val.Grades
			temp.Right = len(rightList)
			temp.Wrong = len(wrongList)
			recentHistory = append(recentHistory,temp)
		}
	}
	res.Wrong = wrong
	res.Right = right
	res.RecentHistory = recentHistory
	return &res,nil
}
func string2IntList(str string)[]int{
	data := strings.Split(str,",")
	res := make([]int,0)
	for _,val := range data{
		i,err :=strconv.ParseInt(val,10,64)
		if err != nil {
			log.Errorf("Fail to parse %v to int ",val)
			continue
		}
		res = append(res,int(i))
	}
	return res
}